package assists.caches
{
	import flash.display.BitmapData;
	import flash.filesystem.File;
	import flash.net.FileReference;
	import flash.utils.ByteArray;
	
	public class CacheFile
	{
		private var _file:File;
		private var _filesList:Array;
		private var _saveImage:SaveImage;
		
		private var imgSaveQueue:Array;
		
		public function CacheFile()
		{
			imgSaveQueue = [];
			
			_saveImage = new SaveImage();
		}
		
		public function fileIsExist(fileName:String):Boolean
		{
			if(fileName == null) return false;
			if(!_file)
			{
				_file = File.documentsDirectory.resolvePath("iWeiHai");
				//				var t2F:File = File.documentsDirectory.resolvePath("iWeiHai/cao.png");
				//				var testF:File = File.applicationDirectory.resolvePath("assets/image/111.png");
				//					trace(File.applicationDirectory.name);
				
				
				if(_file.exists == false)
				{
					_file.createDirectory();
					return false;
				}
			}
			if(!_filesList)
			{
				_filesList = File.applicationDirectory.getDirectoryListing();
				var tmp:File;
				for(var i:int=0;i<_filesList.length;i++)
				{
					tmp = _filesList[i];
					if(tmp.name == fileName)
					{
						return true;
					}
					trace("fileName:" + tmp.name);
				}
			}
			return false;
			
		}
		
		public function saveImage(bitmapData:BitmapData,fileName:String = "ttt.jpg"):void
		{
			//			var fl:File = File.documentsDirectory.resolvePath("iWeiHai/" + fileName);
			//			if(fileName.indexOf("png"))
			//			{
			//				_saveImage.savePng(bitmapData,fl,fileName);
			//			}else
			//			{
			//				_saveImage.saveJpg(bitmapData,fl,fileName);
			//			}
			
			var obj:Object = new Object;
			obj = {img:bitmapData,name:fileName};
			imgSaveQueue.push(obj);
			
			trace(imgSaveQueue + "我了个日" + imgSaveQueue.length);
			
			if(imgSaveQueue.length == 1){
				doTheQueue();
			}
		}
		
		private function doTheQueue():void
		{
			var fl:File = File.documentsDirectory.resolvePath("iWeiHai/" + imgSaveQueue[0].name);
			
			_saveImage.saveImgWithCallback(imgSaveQueue[0].img,fl,imgSaveQueue[0].name,deleteAndContinue);
		}
		
		private function deleteAndContinue(name:String):void
		{
			imgSaveQueue.shift();
			
			if(imgSaveQueue.length > 0){
				doTheQueue();
			}
		}
		
		public function saveXML(data:ByteArray,fileName:String):void
		{
			var fl:File = File.documentsDirectory.resolvePath("iWeiHai/" + fileName);
			_saveImage.saveXML(data,fl,fileName);
		}
	}
}